import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_plus/share_plus.dart';
import '../models/business_card.dart';
import 'business_card_edit_screen.dart';

class BusinessCardDetailScreen extends StatelessWidget {
  final BusinessCard card;

  const BusinessCardDetailScreen({super.key, required this.card});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('名片详情'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) => _handleMenuAction(context, value),
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'edit',
                child: Row(
                  children: [
                    Icon(Icons.edit),
                    SizedBox(width: 8),
                    Text('编辑'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'share',
                child: Row(
                  children: [
                    Icon(Icons.share),
                    SizedBox(width: 8),
                    Text('分享'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'copy',
                child: Row(
                  children: [
                    Icon(Icons.copy),
                    SizedBox(width: 8),
                    Text('复制信息'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue[50]!,
              Colors.white,
            ],
          ),
        ),
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              // 名片图片
              if (card.imagePath != null) _buildImageSection(),
              
              // 基本信息卡片
              _buildInfoCard(
                title: '基本信息',
                children: [
                  _buildInfoRow(Icons.person, '姓名', card.name),
                  _buildInfoRow(Icons.business, '公司', card.company),
                  _buildInfoRow(Icons.work, '職位', card.position),
                ],
              ),

              // 联系方式卡片
              _buildInfoCard(
                title: '联系方式',
                children: [
                  if (card.phone.isNotEmpty)
                    _buildInfoRow(Icons.phone, '电话', card.phone, isClickable: true),
                  if (card.email.isNotEmpty)
                    _buildInfoRow(Icons.email, '电子邮件', card.email, isClickable: true),
                ],
              ),

              // 其他信息卡片
              if (card.address.isNotEmpty || card.website.isNotEmpty)
                _buildInfoCard(
                  title: '其他信息',
                  children: [
                    if (card.address.isNotEmpty)
                      _buildInfoRow(Icons.location_on, '地址', card.address),
                    if (card.website.isNotEmpty)
                      _buildInfoRow(Icons.language, '网站', card.website, isClickable: true),
                  ],
                ),

              // 备注卡片
              if (card.notes != null && card.notes!.isNotEmpty)
                _buildInfoCard(
                  title: '备注',
                  children: [
                    _buildInfoRow(Icons.note, '', card.notes!),
                  ],
                ),

              // 时间信息
              _buildTimeInfo(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildImageSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: Image.network(
          card.imagePath!,
          width: double.infinity,
          height: 250,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              height: 250,
              color: Colors.grey[200],
              child: const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.image,
                      size: 50,
                      color: Colors.grey,
                    ),
                    SizedBox(height: 8),
                    Text(
                      '圖片載入失敗',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildInfoCard({
    required String title,
    required List<Widget> children,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              title,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.blue[800],
              ),
            ),
          ),
          const Divider(height: 1),
          ...children,
        ],
      ),
    );
  }

  Widget _buildInfoRow(
    IconData icon,
    String label,
    String value, {
    bool isClickable = false,
  }) {
    return InkWell(
      onTap: isClickable ? () => _handleClickableAction(label, value) : null,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            Icon(
              icon,
              color: Colors.blue[600],
              size: 20,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (label.isNotEmpty)
                    Text(
                      label,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  if (label.isNotEmpty) const SizedBox(height: 2),
                  Text(
                    value,
                    style: TextStyle(
                      fontSize: 16,
                      color: isClickable ? Colors.blue[600] : Colors.black87,
                      fontWeight: label.isEmpty ? FontWeight.normal : FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
            if (isClickable)
              Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Colors.grey[400],
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildTimeInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Icon(
            Icons.access_time,
            color: Colors.grey[600],
            size: 20,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '创建时间',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  _formatDateTime(card.createdAt),
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
          ),
          if (card.updatedAt != card.createdAt) ...[
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                                  Text(
                  '更新时间',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    _formatDateTime(card.updatedAt),
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  void _handleClickableAction(String label, String value) {
    if (label == '電話') {
      // 拨打电话
      // 这里可以添加拨打电话的逻辑
    } else if (label == '電子郵件') {
      // 发送邮件
      // 这里可以添加发送邮件的逻辑
    } else if (label == '網站') {
      // 打开网站
      // 这里可以添加打开网站的逻辑
    }
  }

  void _handleMenuAction(BuildContext context, String action) {
    switch (action) {
      case 'edit':
        _editCard(context);
        break;
      case 'share':
        _shareCard();
        break;
      case 'copy':
        _copyCardInfo();
        break;
    }
  }

  void _editCard(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BusinessCardEditScreen(card: card),
      ),
    );
    if (result == true) {
      Navigator.pop(context, true);
    }
  }

  void _shareCard() {
    final shareText = '''
${card.name}
${card.companyPosition}

電話: ${card.phone}
郵箱: ${card.email}
${card.address.isNotEmpty ? '地址: ${card.address}' : ''}
${card.website.isNotEmpty ? '網站: ${card.website}' : ''}
''';
    
    Share.share(shareText, subject: '${card.name}的名片');
  }

  void _copyCardInfo() {
    final cardInfo = '''
${card.name}
${card.companyPosition}

電話: ${card.phone}
郵箱: ${card.email}
${card.address.isNotEmpty ? '地址: ${card.address}' : ''}
${card.website.isNotEmpty ? '網站: ${card.website}' : ''}
''';
    
    Clipboard.setData(ClipboardData(text: cardInfo));
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('名片信息已复制到剪贴板'),
        backgroundColor: Colors.green,
      ),
    );
  }
}
